<template>
  <view class="content">
    <view class="header">
	 <div style="flex: 1;">
		<u-search v-model="requestParams.deviceModel" placeholder="请输入设备型号进行搜索" :clearabled="true"
			:showAction="false"></u-search>
	 </div>
	  <div>
		<u-button
			type="primary" 
			size="mini" 
			text="新增设备" 
			@click="handleAddDevice" 
			>
		</u-button>
	  </div>
    </view>
    <view class="main">
      <view class="main_body" v-for="(item, index) in list" :key="index">
        <view class="detail">
          <view class="main_content">
            <view class="main_body_view">
              设备类型：{{ item.name}}
            </view>
          </view>
        </view>
		<view class="button" style="margin-bottom: 10px;">
			<u-button type="primary" size="mini" @click="handleConfirm(item)">确定</u-button>
		</view>
		<view class="footer" />
      </view>
    </view>
	<!-- 新增设备类型弹窗 -->
	<u-modal 
		:show="showDeviceOpen" 
		title="新增设备类型" 
		@confirm="handleConfirmAdd" 
		@cancel="handleCancel" 
		show-cancel-button
		mask-close-able
	  >
		<view>
			<u-form :model="deviceForm" ref="uForm">
				<u-form-item label="设备类型">
					<view style="padding: 8px 6px; border: 1px solid #dadbde; border-radius: 4px; font-size: 15px;">
						<view class="test-scan">
							<view v-if="!deviceForm.deviceTypeId" @click="showOpen = true">请选择设备类型</view>
							<view v-else @click="showOpen = true">{{deviceType}}</view>
							<u-picker 
								:show="showOpen" 
								@confirm="deviceTypeChange" 
								keyName="label" 
								:columns="typeList" 
								@cancel="cancel"
							>
							</u-picker>
						</view>
					</view>
				</u-form-item>
				<u-form-item label="设备品牌">
					<u-input v-model="deviceForm.deviceBrand" placeholder="请输入设备品牌"/>
				</u-form-item>
				<u-form-item label="设备型号">
					<u-input v-model="deviceForm.deviceModel" placeholder="请输入设备品牌"/>
				</u-form-item>
				<u-form-item label="尺寸" v-if="deviceType === '电视机'">
					<u-input v-model="size" placeholder="请输入"/>
				</u-form-item>
				<u-form-item label="处理器" v-if="deviceType === '台式机'">
					<u-input v-model="CPU" placeholder="请输入"/>
				</u-form-item>
				<u-form-item label="处理器" v-if="deviceType === '笔记本'">
					<u-input v-model="specsDevice.CPU" placeholder="请输入"/>
				</u-form-item>
				<u-form-item label="内存" v-if="deviceType === '笔记本'">
					<u-input v-model="specsDevice.memory" placeholder="请输入"/>
				</u-form-item>
				<u-form-item label="硬盘" v-if="deviceType === '笔记本'">
					<u-input v-model="specsDevice.disk" placeholder="请输入"/>
				</u-form-item>
				<u-form-item label="屏幕" v-if="deviceType === '笔记本'">
					<u-input v-model="specsDevice.screen" placeholder="请输入"/>
				</u-form-item>
			</u-form>
		</view>
	</u-modal>
  </view>
</template>

<script>
import request from "@/utils/request.js";
import login from "../../../../store/modules/login";

export default {
  data() {
    return {
		requestParams: {
			deviceModel: '',
			pageNum: 1,
			pageSize: 10,
		},
	    showUnitOpen: false, //单位选择组件
	    size: null, // 电视机
	    CPU: null, // 台式机
	    specsDevice: {
			CPU: null,
			memory: null,
			disk: null,
			screen: null
	    }, // 笔记本
	    searchValue: '', // 搜索值
	    moreForms: [],  // 规格
	    showOpen: false, //类型选择弹窗
	    typeList:[], //类型
	    deviceType: null, // 展示的类型
	    typeIndex : 0,
	    updateCountOpen: false, //修改容器码数量
	    countForm: {}, // 具体数量型号表单
	    countForm1: {
		  countIncrease: 0,
		  countDecrease: 0,
	    },
        deviceList: [], // 设备列表
	    workOrderId: null, // 存储 workId 的变量
	    showDeviceOpen: false, //新增设备弹窗
	    deviceForm: {
		  deviceTypeId: null,
		  deviceBrand: null,
		  deviceModel: null,
		  deviceSpecs: [],
	    }, //新增设备的值
	    formattedDevices: [], // 筛选后的数组
	    list: [], //搜索用的数组
    };
  },
  onLoad(options) {
  	uni.showLoading({
  		title: '正在加载中'
  	})
  	this.getDevice();
	this.getListType()
  	uni.hideLoading()
  },
  onReachBottom() {
  	this.requestParams.pageNum = this.requestParams.pageNum - 0 + 1;
  	this.getDevice()
  },
  watch: {
  	'requestParams.deviceModel'(newVal, oldVal) {
  		this.changeSelect(newVal);
  	}
  },
  methods: {
	  // 筛选数据
	formatDevice() {
		this.formattedDevices = [];
		this.deviceList.map(item =>{
			const { deviceType, deviceBrand, deviceModel, deviceSpecs, deviceTypeId, deviceModelId, ifOnlyOne, count, unit } = item;
			const specsArray = JSON.parse(deviceSpecs || "[]");
			const specsString = specsArray.map(spec => spec[2]).join('/');
			const formattedValue = {
			    name: `${deviceType}/${deviceBrand}/${deviceModel}/${specsString}`,
			    deviceModelId: deviceModelId,
				ifOnlyOne: ifOnlyOne,
				count:count || '',
				unit: unit || '',
				deviceBrand: deviceBrand || '',
				deviceType: deviceType || '',
				deviceModel:deviceModel ||'',
				deviceTypeId: deviceTypeId || '',
				deviceSpecs:deviceSpecs
			};
			this.formattedDevices.push(formattedValue)
			this.list = this.formattedDevices;
		})
	},
	// 模糊搜索
	async searchChange(e) {
		if (e === '') {
		  this.list = this.formattedDevices;
		} else {
		  this.list = this.formattedDevices.filter(item => item.name && item.name.includes(e));
		}
		// this.reset();
	},
	clearSearch() { //清空搜索内容
		this.searchValue = ''
		this.list = this.formattedDevices
	},
	formatDeviceSpecs(specs) {
	    const specs1 = JSON.parse(specs || "[]");
	      if (specs1 && specs1.length > 0) {
		  // 将数组中的第三个元素取出，然后用 '/' 连接
		  const formattedSpecs = specs1.map(spec1 => spec1[2]).join('/');
		  return formattedSpecs;
	     } else {
		  return ''; // 或者显示的默认文本
	    }
	},
	// 获取规格
	setSelect(newVal) {
		this.moreForms.length = 0;
		request({
			url: "system/typeProperties/list",
			method: 'GET',
			data: {
				deviceTypeId: newVal
			   },
			}).then(res => {
				for (const re of res.rows) {
					const arr = [re.devicePropertiesCn, re.devicePropertiesEn, ""];
					this.moreForms.push(arr);
				}
		})
	},
	// 新增设备类型
	handleAddDevice() {
		this.showDeviceOpen = true
	},
	// 新增设备
	handleConfirmAdd() {
		if (this.moreForms.length > 0) {
			if (this.deviceType === '笔记本') {
				for (let i = 0; i < this.moreForms.length; i++) {
				  const key = this.moreForms[i][1];
				  if (this.specsDevice.hasOwnProperty(key)) {
				    this.moreForms[i][2] = this.specsDevice[key];
				  }
				}
			} else if (this.deviceType === "台式机") {
				const cpuItemIndex = this.moreForms.findIndex(item => item[1] === "CPU");
				  // 如果找到，将第三个元素填充为 cpuValue
				  if (cpuItemIndex !== -1) {
				    this.moreForms[cpuItemIndex][2] = this.CPU;
				}
			} else if (this.deviceType === "电视机") {
				const cpuItemIndex = this.moreForms.findIndex(item => item[1] === "size");
				  // 如果找到，将第三个元素填充为 cpuValue
				  if (cpuItemIndex !== -1) {
				    this.moreForms[cpuItemIndex][2] = this.size;
				}
			}
		}
		this.deviceForm.deviceSpecs = JSON.stringify(this.moreForms)
		if (this.deviceForm.deviceTypeId === null) {
			uni.showToast({
				title:"请选择设备类型",
				icon:'none'
			})
			return
		}
		if (this.deviceForm.deviceBrand === null) {
			uni.showToast({
				title:"请选择设备品牌",
				icon:'none'
			})
			return
		}
		if (this.deviceForm.deviceModel === null) {
			uni.showToast({
				title:"请选择设备型号",
				icon:'none'
			})
			return
		}
		request({
			url: "system/modelLibrary",
			method: 'post',
			data: this.deviceForm
		}).then(res => {
			uni.showToast({
				title: '新增设备成功'
			})
			this.reset()
			this.getDevice()
			this.showDeviceOpen = false
		})
	},
	// 重置
	reset() {
		this.size = null
		this.CPU = null
		this.specsDevice = {
			CPU: null,
			memory: null,
			disk: null,
			screen: null
		}
	   this.deviceForm = {
		   deviceTypeId: null,
		   deviceBrand: null,
		   deviceModel: null,
		   deviceSpecs: [],
	   }
	},
	// 取消新增设备弹窗
	handleCancel() {
		this.showDeviceOpen = false
	},
	// 类型选择
	deviceTypeChange(e) {
		this.deviceForm.deviceTypeId = e.value[0].id
		this.deviceType = e.value[0].label
		this.setSelect(e.value[0].id)
		this.cancel()
	},
	
	// 筛选设备类型
	getListType() {
		request({
			url: "system/type/list",
			method: 'get'
		}).then(res => {
			this.typeList = res.data.map(item => {
			    return {
			      label: item.code,
			      id: item.id
			    };
			});
			this.typeList = [this.typeList];
		})
	},
	// 取消选择设备
	cancel() {
		this.showOpen = false
	},
	// 确定数据
	handleConfirm(item) {
		let pages = getCurrentPages() // 获取当前页面栈的实例，以数组形式按栈的顺序给出，第一个元素为首页，最后一个元素为当前页面。
		let prevPage = pages[pages.length - 2] //上一页页面实例
		uni.navigateBack({
			delta:1,
			success:() => {
				prevPage.$vm.otherFunContainer(item) // 给上一页绑定方法otherFun,传参地址id
			}
		})
	},
	// 设备列表
    getDevice() {
      request({
        method: "GET",
        url: "system/modelLibrary/list",
		data: this.requestParams
      }).then((res) => {
        this.requestParams.pageNum -= (!res.rows);
        if (this.deviceList.length < res.total) {
          this.deviceList = this.deviceList.concat(res.rows);
          this.formatDevice()
        }
      });
    },
	changeSelect(item) {
		uni.showLoading({
			title: "正在加载中"
		})
		this.requestParams.deviceModel = item + '';
		this.requestParams.pageNum = 1;
		this.deviceList.length = 0;
		this.getDevice();
		uni.hideLoading()
	}
  },
};
</script>

<style lang="scss" scoped>
	.content {
		background: rgb(244, 249, 254);
		.header {
			position: sticky;
			top: 0;
			z-index: 999;
			display: flex;
			align-items: center;
			overflow: hidden;
			background:#f4f9fe;
			box-shadow:0px 3px 10px rgba(0, 124, 233, 0.16);
			margin-bottom: 10upx;
			/deep/ .u-search__content {
				background-color: #ffffff !important;
			}
			/deep/ .u-search__content__input {
				background-color: #ffffff !important;
			}
		}
		
		.main {
			margin-bottom: 100px;
			.main_body {
				background-color: rgb(226, 241, 255);
				margin: 20upx;
				border-radius: 2%;
				border:1px solid;
				border-color:rgba(0, 124, 233, 0.4);
				.title {
					border-bottom:1px solid;
					border-color:rgb(140, 196, 246);
					padding: 20upx;
					.main_body_view {
						margin: 10upx;
					}
					.main_body_view_title {
						margin-bottom: 10upx;
					}
				}
				.main_content {
					padding: 20upx;
					background-color: #ffffff;
				}
				
				.button {
					position: absolute;
					right: 100upx;
					width: 40rpx;
				}
				.footer{
					height:30px;
					background-color: #ffffff;
					border-bottom-left-radius: 15upx;
					border-bottom-right-radius: 15upx;
				}
			}
		}	
		.tabbar {
			position: sticky;
			bottom: 30upx;
			z-index: 999;
		}
	}
</style>